package com.yunshang.shoppingmall.shopping.Weixin;

import com.yunshang.shoppingmall.Methods.FinaceMethods;
import com.yunshang.shoppingmall.common.MessageConstants;
import com.yunshang.shoppingmall.common.Response;
import com.yunshang.shoppingmall.common.weixin.*;
import com.yunshang.shoppingmall.controller.product.ProductController;
import com.yunshang.shoppingmall.entity.*;
import com.yunshang.shoppingmall.service.*;
import com.yunshang.shoppingmall.service.Finace.FinaceService;
import com.yunshang.shoppingmall.service.Finace.FinaceTotalService;
import com.yunshang.shoppingmall.service.User.UserRankService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.yunshang.shoppingmall.Methods.FinaceMethods.insertFinaceU;
import static com.yunshang.shoppingmall.common.OrderHelper.operOrderDetailsProduct;
import static com.yunshang.shoppingmall.common.weixin.HttpRequest.getUTF8XMLString;

@Controller
@RequestMapping("/API/Weixin/")
public class WeixinPayApi {
     public  static String severUrl="http://www.ycsqd.com";
    @Autowired
    OrderService orderService;
    @Autowired
    ConfigService configService;
    @Autowired
    FinaceService finaceService;
    @Autowired
    FinaceTotalService finaceTotalService;
    @Autowired
    SysUserNoService sysUserNoService;
    @Autowired
    UserRankService userRankService;
    @Autowired
    UserNoAchievementService userNoAchievementService;

    @Autowired
    CartService cartService;


    @Autowired
    OrderDetailsService orderDetailsService;
    @RequestMapping("/OrderPay")

    //发起支付页面
    public String OrderPay() {
        return "shoppingApi/order/OrderPay";
    }

    @RequestMapping("/token")
    //微信登录获取Openid下单
    public ModelAndView token(HttpServletRequest request, HttpServletResponse response, String openid) {
        ModelAndView modelAndView = new ModelAndView("shoppingApi/order/token");
        HttpSession session = request.getSession();
        PayOrder payOrder = (PayOrder)session.getAttribute("payOrder");
        if(openid!=null && !openid.isEmpty())
        {
            session.setAttribute("openid",openid);
            if(session.getAttribute("payOrder")!=null){
                String out_trade_no = payOrder.getOut_trade_no();
                String total_fee = payOrder.getTotal_fee();
                System.out.println("a3:"+total_fee);
                String attach = payOrder.getAttach();
                String body = payOrder.getBody();
                session.removeAttribute("payOrder");
                //return out_trade_no;
                String prepay_id = WeChat.downOrderJSAPI(request, response, out_trade_no, total_fee, attach, body,openid);
                if(prepay_id!=null)
                {
                    String timeStamp = DateUtil.timeStamp();
                    Map<String, String> paramsMap1 = new HashMap<>();
                    paramsMap1.put("appId", WeChat.appid);
                    paramsMap1.put("timeStamp", timeStamp);
                    paramsMap1.put("package", "prepay_id="+prepay_id);
                    paramsMap1.put("nonceStr", "15513fds");
                    paramsMap1.put("signType", "MD5");
                    // 获取签名
                    String sign = "";
                    try {
                        sign = WeChat.getPayCustomSign(paramsMap1, WeChat.paykey);
                        System.out.println("生成请求签名成功");
                    } catch (Exception e) {
                        System.out.println("生成请求签名失败");
                    }
                    paramsMap1.put("paySign", sign);
                    modelAndView.addObject("JSAPI",paramsMap1);
                    modelAndView.addObject("orderNo",out_trade_no);
                }
            }
        }
        if(payOrder!=null){
            modelAndView.addObject("orderNo",payOrder.getOut_trade_no());
        }
        return modelAndView;
    }

    @RequestMapping(value = "/downOrder")
    @ResponseBody
    public String downOrder(HttpServletRequest request, HttpServletResponse response, String out_trade_no,String cash) throws IOException, ServletException {
        System.out.println("out_trade_no:"+out_trade_no);
        if (out_trade_no.isEmpty()) {
            return "{\"msgCode\":\"-1\",\"detail\":\"请填写订单编号!!\"}";
        }
        List<Order> orders=orderService.selectListOrderCartByNo(out_trade_no);
        for (Order order:orders) {
            String orderno1=order.getCartOrderno()==null?"":order.getCartOrderno();
            if("".equals(orderno1)){
                return "{\"msgCode\":\"-1\",\"detail\":\"数据有误，请返回下单重试!!\"}";
            }
        }
        System.out.println(cash+"---");
        request.getSession().setAttribute("or"+out_trade_no,cash);
        String total_fee = AmountUtils.changeY2F(cash);
        String attach = "attach";
        String body= "ycsqd";
//        try {body = getUTF8XMLString("荟生零售商品");}catch (Exception e){}
        try {body = getUTF8XMLString("ycsqd");}catch (Exception e){}
        HttpSession session = request.getSession();
        PayOrder payOrder = new PayOrder();
        payOrder.setOut_trade_no(out_trade_no);
        payOrder.setTotal_fee(total_fee);
        payOrder.setAttach(attach);
        payOrder.setBody(body);
        session.setAttribute("payOrder",payOrder);
        if(UserRequest.IsWeixin(request)) {
            try {
                Order order=orders.get(0);
                order.setOrderMessage("1");
                orderService.updateByPrimaryKeySelective(order);
            }catch (Exception e){

            }
            //公众号支付
            if (session.getAttribute("openid") == null) {
                try {
                    response.sendRedirect("/API/Weixin/code?out_trade_no="+out_trade_no);//重定向到
                } catch (IOException e) {
                }
                return "";
            }else {
                try {
                    response.sendRedirect("/API/Weixin/token?openid="+session.getAttribute("openid").toString());
                } catch (IOException e) {
                }
                return "";
            }
        }
        else {
            if(UserRequest.IsMoblie(request)) {
                try {
                    Order order=orders.get(0);
                    order.setOrderMessage("1");
                    orderService.updateByPrimaryKeySelective(order);
                }catch (Exception e){

                }
                System.out.println("H5支付");
                return WeChat.downOrderH5(request, response, out_trade_no, total_fee, attach, body);
            }else{
                return "{\"msgCode\":\"-1\",\"detail\":\"请使用手机浏览器\"}";
            }
        }
    }

    //微信支付成功异步回调地址
    @RequestMapping(value = "/OrderURL")
    @ResponseBody
    public Object OrderURL(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("微信支付成功异步回调");
        HttpSession session = request.getSession();
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        int memberLevel=0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
            memberLevel= userNo1.getRank();
        }

        System.out.println("A");
        //读取参数
        InputStream inputStream;
        String s;
        StringBuffer sb = new StringBuffer();
        try {
            inputStream = request.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            try {while ((s = in.readLine()) != null) {
                    sb.append(s);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {in.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(sb.toString());
        String result = sb.toString();
        Map<String, String> resultMap = null;
        // 获取支付结果
        //订单编号
        String out_trade_no = "",total_fee,attach,nonce_str,openid;
        //订单金额 附加消息 随机字符串 openid
        String r="";
        if (result.indexOf("SUCCESS") != -1) {
            try {
                resultMap = WeChat.xmlToMap(result);
            } catch (Exception e) {
            }

            if (resultMap != null) {
                out_trade_no = resultMap.get("out_trade_no");
                attach = resultMap.get("attach");
                openid = resultMap.get("openid");
                total_fee = resultMap.get("total_fee");
                nonce_str = resultMap.get("nonce_str");
                System.out.println("订单编号--->" + out_trade_no);System.out.println("订单金额--->" + total_fee);
                System.out.println("openid--->" + openid);System.out.println("附加消息--->" + attach);
                //判断支付信息
                PayOrder payOrder = WeChat.orderData.get(out_trade_no);
                if (payOrder != null) {
                    if (payOrder.getAttach().equals(attach) && payOrder.getTotal_fee().equals(total_fee)) {
                        System.out.println("BB--->" );
                        if(WeChat.getOrder(out_trade_no,payOrder.getTotal_fee()))
                        {
                            Config config=configService.selectByPrimaryKey(1);
                            String financeName=config.getFinacename3();
                            Integer cashCouponMul= config.getCashcouponmul();
                            Order order=orderService.selectByNo(out_trade_no);
                            BigDecimal backCashCoupon=BigDecimal.valueOf(order.getBackCashcoupon()*cashCouponMul);
                            BigDecimal cash=BigDecimal.valueOf(Integer.parseInt(total_fee)/100);

                            int resf= FinaceMethods.insertFinaceU(1, cash,memberUserId,out_trade_no,memberUserId,112);//保存积分

                            if(resf<=0){
                                System.out.println("支付写入数据库失败" );
                                //日志or数据库
                            }
                            //处理数据
                            BigDecimal amount4=BigDecimal.valueOf(0.00);
                            BigDecimal amount1=BigDecimal.valueOf(0.00);
                            try {
                                amount4=order.getCostInter();//消费积分
                                amount1=order.getInter();//积分
                            }catch (Exception e){

                            }
                            if(amount4.doubleValue()>0){
                                Integer res1=insertFinaceU(4,amount4,memberUserId,order.getOrderNo()+"购物支付!",memberUserId,111);
                                if(res1<=0){
                                    //return new Response(MessageConstants.MSG_SYS_ERROR, -1, "消费积分扣除有误，支付失败!");
                                }
                            }
                            if(amount1.doubleValue()>0){
                                Integer res2=insertFinaceU(1,amount1,memberUserId,order.getOrderNo()+"购物支付!",memberUserId,111);
                                if(res2<=0){
                                    //return new Response(MessageConstants.MSG_SYS_ERROR, -1, "积分扣除有误，支付失败!");
                                }
                            }
                            //返代金券
                            Integer ress=FinaceMethods.insertFinaceU(3,backCashCoupon,memberUserId,order.getOrderNo()+"返"+financeName,memberUserId,999);//折扣券
                            if(ress<=0){

                            }
                        //设置订单状态
                        payOrder.setOrderState("702");
                        Integer res3=orderService.updateOrderStatus("702",out_trade_no);
//                        String url=severUrl+"/wap/getOrderDetails?orderNo="+out_trade_no;
//                            try {
//                                response.sendRedirect(url);
//                            }catch (Exception e){
//
//                            }
                            r = "<xml> \n" +
                                    "\n" +
                                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                                    "   <return_msg><![CDATA[OK]]></return_msg>\n" +
                                    " </xml> \n";
                        }
                    }
                }
            }
        }
        if(r.isEmpty())
        {
            r = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }

        return r;
    }

    @RequestMapping(value = "/getURL")
    @ResponseBody
    public Object getURL(HttpServletRequest request, HttpServletResponse response) {
        String url = request.getQueryString();
        return url;
    }

    //查询订单状态
    @RequestMapping(value = "/getQj")
    @ResponseBody
    public String getQj(HttpServletRequest request, HttpServletResponse response, String key) {
        System.out.println("查询订单状态");
        PayOrder payOrder = WeChat.orderData.get(key);
        String str="{\"errorDetail\":\"支付中\"}";
        if(payOrder!=null) {
            if (payOrder.getOrderState().equals("702")) {
                str = "{\"msgCode\":\"000000\"}";
            }
        }
        return str;
    }

    @RequestMapping(value = "/getBill")
    @ResponseBody
    public List<BillOrder> getBill(HttpServletRequest request, HttpServletResponse response, String date) {
        if(date.isEmpty())
        {
            return null;
        }
        return WeChat.getBILL(date);
    }


    //微信支付成功处理数据
    @RequestMapping(value = "/orderCallback")
    @ResponseBody
    public Response orderCallback(HttpServletRequest request, HttpServletResponse response,String orderNo) throws Exception {
            PayOrder payOrder = WeChat.orderData.get(orderNo);
            payOrder.setOrderState("702");
            HttpSession session = request.getSession();
            UserNo userNo1 = (UserNo)session.getAttribute("userNo");
            int memberUserId=0;
            if(userNo1!=null){
                memberUserId=userNo1.getId();
            }
            BigDecimal cash;
            try {
                cash=BigDecimal.valueOf(Double.parseDouble(payOrder.getTotal_fee())/100.00);
            }catch (Exception e){
                cash=BigDecimal.valueOf(0);
            }
            currencyDeduction(memberUserId+"",orderNo,cash+"",request);
            return new Response(MessageConstants.MSG_SYS_ERROR,1,orderNo);
    }

    /***
     * 查询订单
     * @param out_trade_no
     * @param total_fee
     * @return
     */
    @RequestMapping(value = "/getOrder")
    @ResponseBody
    public  boolean getOrder(String out_trade_no,String total_fee) throws Exception {
        return WeChat.getOrder(out_trade_no,total_fee);
    }

    @RequestMapping(value = "/H5Callback")
    @ResponseBody
    public ModelAndView H5Callback(HttpServletResponse response,HttpServletRequest request) throws IOException {
        HttpSession session= request.getSession();
        PayOrder payOrder=(PayOrder) session.getAttribute("payOrder");
        ModelAndView modelAndView=new ModelAndView("shoppingApi/order/orderQuery");
        DecimalFormat df = new DecimalFormat("#0.00");//显示格式
        String orderNo="";
        if(payOrder!=null){
            orderNo = payOrder.getOut_trade_no();
        }
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();
        }
        //orderNo="201903061115449867";
        Map<String, Object> map = new HashMap<>();
        Order order = orderService.selectByNo(orderNo);//根据订单号查询订单
        /*查询用户的积分*/
        FinaceTotal finaceTotal = new FinaceTotal();
        finaceTotal.setfType("1");//积分
        finaceTotal.setUserId(memberUserId);
        Double inter = 0.00;
        FinaceTotal finaceTotals = FinaceMethods.selectFinaceBalace(finaceTotal);//积分
        if (finaceTotals != null) {
            inter = finaceTotals.getBalance();
        }
        Double inter1 = inter;
        /*查询用户的消费积分*/
        finaceTotal.setfType("4");
        Double costinter = 0.00;
        FinaceTotal finaceTotals2 = FinaceMethods.selectFinaceBalace(finaceTotal);//消费积分
        if (finaceTotals2 != null) {
            costinter = finaceTotals2.getBalance();
        }
        Config config1 = configService.selectByPrimaryKey(1);//货币名称显示
        map.put("WebConfig", config1);
        map.put("order", order);
        map.put("inter", inter);//积分
        map.put("costinter", costinter);//消费积分
        modelAndView.addObject("orderPay", map);
        return modelAndView;
    }


    @RequestMapping(value = "/H5CallbackQuery")
    @ResponseBody
    //微信H5支付订单查询
    public boolean H5CallbackQuery(HttpSession session,String No,String cash,HttpServletRequest request) throws Exception {
        //System.out.println("No:"+No+" cash:"+cash);//64564645454554  0.02
        UserNo userNo1 = (UserNo)session.getAttribute("userNo");
        String cash1= (String) session.getAttribute("or"+No);
        int memberUserId=0;
        if(userNo1!=null){
            memberUserId=userNo1.getId();
        }
            String out_trade_no=No,total_fee=cash1;
            //微信支付成功 充值积分
            boolean bools= WeChat.getOrder(out_trade_no,total_fee);
            if(bools) {
                return (currencyDeduction(memberUserId + "", out_trade_no, total_fee, request));
            }else {
                return false;
            }
    }


    @RequestMapping(value = "/test1")
    @ResponseBody
    //微信H5支付订单查询
    public boolean test1(HttpServletRequest request,String No,String cash) throws Exception {


        //currencyDeduction("1000727",No,cash,request);
        return true;
    }
    @RequestMapping(value = "/test11")
    @ResponseBody
    //微信H5支付订单查询
    public boolean test11(String cash) throws Exception {
//        cash="274.01";
//        String total_fee1=AmountUtils.changeF2Y(cash);
        return true;
    }

    //支付成功 扣除相应货币
   // @Transactional(rollbackFor = Exception.class)
    public boolean currencyDeduction(String userNoId1,String orderNo,String cash,HttpServletRequest request)throws Exception {
            HttpSession session=request.getSession();
            Order order=orderService.selectByNo(orderNo);
            String orderState=order.getOrderStatus()==null?"0":order.getOrderStatus();
            if(orderState.equals("702")){
                return false;
            }
            Config config=configService.selectByPrimaryKey(1);
            int userNoId=Integer.parseInt(userNoId1);
            FinaceTotal finaceTotal=finaceTotalService.selectFinaceBalaceAll(userNoId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            String date1 = sdf.format(date);

            double balance=0;
        UserNo userNo1 = (UserNo) session.getAttribute("userNo");
        int memberUserId = 0,memberLevel = 0,ids = 0,userNoReCommendId=0;//推荐人id
        UserRank  userRank=null;
        UserRank recommendUserRank=null;//推荐人的等级
        UserNo recommendUserNo=null;
        int recommendRankId=0;
        double recommendCommission=0.00;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();//用户编号ID
            memberLevel = userNo1.getRank();
            userNoReCommendId=userNo1.getRecommend();
            userRank=userRankService.selectByPrimaryKey(memberLevel);//用户等级
            recommendUserNo=sysUserNoService.selectByPrimaryKey(userNoReCommendId);
            if(recommendUserNo!=null){
                recommendRankId=recommendUserNo.getRank();
                recommendUserRank=userRankService.selectByPrimaryKey(recommendRankId);
                if(recommendUserRank!=null){
                    recommendCommission=recommendUserRank.getCommission();
                }
            }
        }
        //推荐人积分
        double recommendBalance=0.00;
        int recommendFId=0;
        FinaceTotal f=new FinaceTotal();
        f.setUserId(userNoReCommendId);
        f.setfType("1");
        FinaceTotal recommendFinaceTotal = FinaceMethods.selectFinaceBalace(f); //推荐人积分
        if(recommendFinaceTotal!=null){
            recommendFId=recommendFinaceTotal.getfId();
            recommendBalance=recommendFinaceTotal.getBalance();
        }
            Boolean bools=true;
            double amount;
            Boolean strResult = cash.matches("-?[0-9]+.*[0-9]*");
            if(strResult==false){
                amount=0;
            }else {
                amount=Double.parseDouble(cash);
            }

            if(amount>0){//现金支付是否大于0
                FinaceToData finaceToData = new FinaceToData();
                finaceToData.setUserId(userNoId);//用户编号Id
                finaceToData.setFinaceType("777");
                finaceToData.setRemark("充值"+orderNo);
                finaceToData.setClassify(1);
                finaceToData.setFinaceTime(Timestamp.valueOf(date1));//时间
                finaceToData.setAmount(BigDecimal.valueOf(amount));//积分
                //用户积分的余额
                finaceToData.setBalance(BigDecimal.valueOf(finaceTotal.getBalance1() + amount));
                finaceToData.setOpratorUId(userNoId);
                int res = finaceService.insertFinaceData(finaceToData);
                if(res<=0){
                    bools=false;
                    System.out.println("Classify1");
                    Logger logger= LoggerFactory.getLogger("Classify1"+orderNo);
                    //throw new RuntimeException();
                }
            }
            BigDecimal amount1;
            if(order.getRealPay()!=null&&order.getFreight()!=null){
                Boolean strResult1 = order.getRealPay().toString().matches("-?[0-9]+.*[0-9]*");
                Boolean strResult2 = order.getFreight().toString().matches("-?[0-9]+.*[0-9]*");
                if(strResult1==false||strResult2==false){
                    amount1=BigDecimal.valueOf(0);
                }else {
                    amount1=BigDecimal.valueOf(order.getRealPay()).add(order.getFreight());
                }
            }else {
                amount1=BigDecimal.valueOf(0);
            }
            if(amount1.doubleValue()>0){//实际支付总金额
                FinaceToData finaceToData1 = new FinaceToData();
                finaceToData1.setUserId(userNoId);//用户编号Id
                finaceToData1.setFinaceType("111");
                finaceToData1.setRemark("支出"+orderNo);
                finaceToData1.setClassify(1);
                finaceToData1.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal costinter=order.getCostInter()==null?BigDecimal.valueOf(0):order.getCostInter();
                BigDecimal am=amount1.subtract(costinter);
                finaceToData1.setAmount(new BigDecimal(-am.doubleValue()));//积分
                balance=(finaceTotal.getBalance1()+amount+costinter.doubleValue())-amount1.doubleValue();
                finaceToData1.setBalance(BigDecimal.valueOf(balance));
                finaceToData1.setOpratorUId(userNoId);
                int res1 = finaceService.insertFinaceData(finaceToData1);
                if(res1<=0){
                    bools=false;
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(balance);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("1");
                    int cosRow;
                    if(finaceTotal.getfId1()>0){
                        finaceTotal4.setfId(finaceTotal.getfId1());
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        bools=false;
                        System.out.println("Classify1c");
                        Logger logger= LoggerFactory.getLogger("Classify1c"+orderNo);
                        //消费积分扣除有误，支付失败!
                        //throw new RuntimeException();
                    }
                }
            }
            if(order.getCostInter()!=null){//订单实际支付使用的消费积分
                if(order.getCostInter().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(4);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCostInter();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance4()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //消费积分扣除有误
                        bools=false;
                        System.out.println("Classify4");
                        Logger logger= LoggerFactory.getLogger("Classify4"+orderNo);
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId4());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance4()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("4");
                        int cosRow;
                        if(finaceTotal.getfId4()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify4a");
                            Logger logger= LoggerFactory.getLogger("Classify4a"+orderNo);
                            //消费积分扣除有误，支付失败!
                            //throw new RuntimeException();
                        }
                    }
                }
            }
            if(order.getCoupon()!=null){
                if(order.getCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(2);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance2()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        //购物券扣除有误
                        bools=false;
                        System.out.println("Classify2b");
                        Logger logger= LoggerFactory.getLogger("Classify2b"+orderNo);
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId2());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance2()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("2");
                        int cosRow;
                        if(finaceTotal.getfId2()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify2c");
                            Logger logger= LoggerFactory.getLogger("Classify2c"+orderNo);
                            //消费积分扣除有误，支付失败!
                            //throw new RuntimeException();
                        }
                    }
                }
            }
            if(order.getCashCoupon()!=null){
                if(order.getCashCoupon().doubleValue()>0){
                    FinaceToData finaceToData2 = new FinaceToData();
                    finaceToData2.setUserId(userNoId);//用户编号Id
                    finaceToData2.setFinaceType("111");
                    finaceToData2.setRemark("支出"+orderNo);
                    finaceToData2.setClassify(3);
                    finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                    BigDecimal amount2=order.getCashCoupon();
                    finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                    finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance3()) - amount2.doubleValue()));
                    finaceToData2.setOpratorUId(userNoId);
                    int res2 = finaceService.insertFinaceData(finaceToData2);
                    if(res2<=0){
                        bools=false;
                        System.out.println("Classify3a");
                        Logger logger= LoggerFactory.getLogger("Classify3a"+orderNo);
                        //代金券扣除有误
                        //throw new RuntimeException();
                    }else {
                        //更新财务余额
                        FinaceTotal finaceTotal4=new FinaceTotal();
                        finaceTotal4.setfId(finaceTotal.getfId3());
                        finaceTotal4.setOpratorId(userNoId);
                        finaceTotal4.setBalance(((finaceTotal.getBalance3()) - amount2.doubleValue()));
                        finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                        finaceTotal4.setOpratorUId(userNoId);
                        finaceTotal4.setUserId(userNoId);
                        finaceTotal4.setfType("3");
                        int cosRow;
                        if(finaceTotal.getfId3()>0){
                            cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                        }else {
                            cosRow =finaceTotalService.insertSelective(finaceTotal4);
                        }
                        if (cosRow <= 0) {
                            bools=false;
                            System.out.println("Classify3b");
                            Logger logger= LoggerFactory.getLogger("Classify3b"+orderNo);
                        }
                    }
                }
            }
            //返还折扣券保存到数据库返finance3_table
            Integer cashCouponMul = 0;
            String financeName = "";
            if(config!=null){
                if(config.getCashcouponmul()!=null){
                    cashCouponMul = config.getCashcouponmul();//返折扣券的倍数 ---2倍
                }
                if(config.getFinacename3()!=""||config.getCashcouponmul()!=null){
                    financeName = config.getFinacename3();//返回----折扣券的名称
                }
            }
            if(cashCouponMul>0){
                int resf = FinaceMethods.insertFinaceU(3, BigDecimal.valueOf(order.getBackCashcoupon() * cashCouponMul), userNoId, order.getOrderNo() + "返" + financeName, userNoId, 999);
            }
            //更新会员等级
            if (memberLevel == 19) {
                userNo1.setRank(16);
                int resu = sysUserNoService.updateByPrimaryKeySelective(userNo1);
                if (resu <= 0) {
                    //日志or数据库
                    bools=false;
                    System.out.println("bbbb");
                    Logger logger= LoggerFactory.getLogger("bbbb"+orderNo);
                    //throw new RuntimeException();
                }
            }
            order.setOrderStatus("702");
            order.setPayStatus("1");
            order.setPayTime(new Date());
        //添加记录运营成本到用户业绩表
        double opratorCost=0.00;//订单运营成本
        UserNoAchievement userNoAchievement=new UserNoAchievement();
        userNoAchievement.setOpratorCostSign("0");//为结算的业绩标志
        userNoAchievement.setUserNoId(memberUserId);
        userNoAchievement.setPayTime(new Timestamp(order.getpOrderTime().getTime()));
        if(order!=null&&order.getOpratorCost()!=null){
            order.getOpratorCost().doubleValue();
        }
        userNoAchievement.setOrderId(order.getOrderId());
        userNoAchievement.setOrderOpratorCost(opratorCost);
        if(opratorCost>0) {
            int achievementRow = userNoAchievementService.insertSelective(userNoAchievement);
            //添加记录运营成本到用户业绩表
        }
        //分享赚
        if(userNoReCommendId<=0){//没有推荐人默认为零散会员编号id为62240
            userNoReCommendId=62240;
        }
        if(userNoReCommendId>0){//是否有推荐人
            double orderProfit=order.getOrderProfit();//订单利润
            double shareEaring=0.00;
            if(recommendCommission-userRank.getCommission()>0){
                shareEaring=orderProfit*(recommendCommission-userRank.getCommission())/100;
            }
            if(shareEaring>0){
                FinaceToData finaceToDataRe = new FinaceToData();
                finaceToDataRe.setUserId(userNoReCommendId);//推荐人用户编号Id
                finaceToDataRe.setFinaceType("888");
                finaceToDataRe.setRemark("分享赚"+orderNo);
                finaceToDataRe.setClassify(1);
                finaceToDataRe.setFinaceTime(Timestamp.valueOf(date1));//时间
                finaceToDataRe.setAmount(new BigDecimal(shareEaring));//积分
                finaceToDataRe.setBalance(new BigDecimal(shareEaring+recommendBalance));
                finaceToDataRe.setOpratorUId(userNoReCommendId);
                int row1 = finaceService.insertFinaceData(finaceToDataRe);
                if(row1<=0){
                    bools=false;
                    System.out.println("12");
                    Logger logger= LoggerFactory.getLogger("12"+orderNo);
                    //throw new RuntimeException();
                }
                FinaceTotal finaceTotal4=new FinaceTotal();
                finaceTotal4.setOpratorId(userNoReCommendId);
                finaceTotal4.setBalance(recommendBalance+shareEaring);
                finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                finaceTotal4.setOpratorUId(userNoReCommendId);
                finaceTotal4.setUserId(userNoReCommendId);
                finaceTotal4.setfType("1");
                int recommendF;
                if(recommendFId>0){
                    finaceTotal4.setfId(recommendFId);
                    recommendF=finaceTotalService.updateByPrimaryKey(finaceTotal4);
                }else {
                    recommendF=finaceTotalService.insertSelective(finaceTotal4);
                }
                if(recommendF<=0){
                    bools=false;
                    System.out.println("122");
                    Logger logger= LoggerFactory.getLogger("122"+orderNo);
                    //throw new RuntimeException();
                }
            }

        }
        //分享赚
        orderService.activity(order,memberUserId+"",userRank.getCommission(),userNoReCommendId,balance);
        Integer res3=orderService.updateByPrimaryKeySelective(order);
        if(res3<=0){
            bools=false;
            System.out.println("vvv");
            Logger logger= LoggerFactory.getLogger("vvv"+orderNo);
            //throw new RuntimeException();
        }
            return bools;
    }

    @RequestMapping(value = "/upOrder")
    @ResponseBody
    public String upOrder(HttpServletRequest request, HttpServletResponse response, String out_trade_no,String inters,String costinters) {
        Order order=orderService.selectByNo(out_trade_no);
        Boolean strResultx1 = inters.matches("-?[0-9]+.*[0-9]*");
        Boolean strResultx2 = costinters.matches("-?[0-9]+.*[0-9]*");
        double intersX=0,costIntersX=0;
        if(strResultx1){
            intersX=Double.parseDouble(inters);
        }
        if(strResultx2){
            costIntersX=Double.parseDouble(costinters);
        }
        order.setCostInter(new BigDecimal(costIntersX));
        order.setInter(new BigDecimal(intersX));
        int res= orderService.updateByPrimaryKeySelective(order);
        if(res>0){
            return "{\"msgCode\":\"1\",\"detail\":\"---\"}";
        }else {
            return "{\"msgCode\":\"-1\",\"detail\":\"---\"}";
        }
    }

    @RequestMapping(value = "/dealOrder")
    @ResponseBody
    public void dealOrder(){
        List<String> orderList=new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String date1 = sdf.format(date);
        double balance=0;
        for (String strNo:orderList ) {
            Order order=orderService.selectByNo(strNo);
            double lirun=order.getOrderProfit()==null?0:order.getOrderProfit();
            int userid=order.getUserId();
            UserNo userNo=sysUserNoService.selectByPrimaryKey(userid);
            UserRank userRank=userRankService.selectByPrimaryKey(userNo.getRank());
            double commi=userRank.getCommission()/100;
            double membersave=lirun*commi;

            FinaceTotal finaceTotal=finaceTotalService.selectFinaceBalaceAll(userid);

                FinaceToData finaceToData1 = new FinaceToData();
                finaceToData1.setUserId(userid);//用户编号Id
                finaceToData1.setFinaceType("222");
                finaceToData1.setRemark("补会员节省"+strNo);
                finaceToData1.setClassify(1);
                finaceToData1.setFinaceTime(Timestamp.valueOf(date1));//时间
                //BigDecimal costinter=order.getCostInter()==null?BigDecimal.valueOf(0):order.getCostInter();
                BigDecimal am=BigDecimal.valueOf(membersave);
                finaceToData1.setAmount(new BigDecimal(-am.doubleValue()));//积分
                balance=finaceTotal.getBalance1()+membersave;
                finaceToData1.setBalance(BigDecimal.valueOf(balance));
                finaceToData1.setOpratorUId(userid);
                int res1 = finaceService.insertFinaceData(finaceToData1);
                if(res1<=0){

                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setOpratorId(userid);
                    finaceTotal4.setBalance(balance);
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userid);
                    finaceTotal4.setUserId(userid);
                    finaceTotal4.setfType("1");
                    int cosRow;
                    if(finaceTotal.getfId1()>0){
                        finaceTotal4.setfId(finaceTotal.getfId1());
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                    }
                }
        }
    }

    @RequestMapping(value = "/deal")
    @ResponseBody
    public void deal()  {
        List<String> orderList=new ArrayList<>();
        orderList.add("");
        for (String orderNo1:orderList ) {
            String orderNo=orderNo1;
        Order order=orderService.selectByNo(orderNo);
            String orderState=order.getOrderStatus()==null?"0":order.getOrderStatus();
            if(orderState.equals("702")){
                return ;
            }
        Config config=configService.selectByPrimaryKey(1);

            String userNoId1="";
        if(order.getUserId()!=null){
            userNoId1=order.getUserId().toString();
        }else {
            Cart cart=cartService.selectByOrderNo(orderNo).get(0);
            if(cart!=null){
                userNoId1=cart.getUserId().toString();
            }
        }
//            getRealPay+getFreight-getInter-getCostInter
        UserNo userNoSS=sysUserNoService.selectByPrimaryKey(Integer.parseInt(userNoId1));
        String cash=(order.getRealPay()+order.getFreight().doubleValue()-order.getInter().doubleValue()-order.getCostInter().doubleValue())+"";
        double balance=0;
        int userNoId=Integer.parseInt(userNoId1);
        FinaceTotal finaceTotal=finaceTotalService.selectFinaceBalaceAll(userNoId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String date1 = sdf.format(date);


        UserNo userNo1 = userNoSS;

        int memberUserId = 0,memberLevel = 0,ids = 0,userNoReCommendId=0;//推荐人id
        UserRank  userRank=null;
        UserRank recommendUserRank=null;//推荐人的等级
        UserNo recommendUserNo=null;
        int recommendRankId=0;
        double recommendCommission=0.00;
        if (userNo1 != null) {
            memberUserId = userNo1.getId();//用户编号ID
            memberLevel = userNo1.getRank();
            userNoReCommendId=userNo1.getRecommend();
            userRank=userRankService.selectByPrimaryKey(memberLevel);//用户等级
            recommendUserNo=sysUserNoService.selectByPrimaryKey(userNoReCommendId);
            if(recommendUserNo!=null){
                recommendRankId=recommendUserNo.getRank();
                recommendUserRank=userRankService.selectByPrimaryKey(recommendRankId);
                if(recommendUserRank!=null){
                    recommendCommission=recommendUserRank.getCommission();
                }
            }
        }
        //推荐人积分
        double recommendBalance=0.00;
        int recommendFId=0;
        finaceTotal.setUserId(userNoReCommendId);
        finaceTotal.setfType("1");
        FinaceTotal recommendFinaceTotal = FinaceMethods.selectFinaceBalace(finaceTotal); //推荐人积分
        if(recommendFinaceTotal!=null){
            recommendFId=recommendFinaceTotal.getfId();
            recommendBalance=recommendFinaceTotal.getBalance();
        }


        Boolean bools=true;
        double amount;

        Boolean strResult = cash.matches("-?[0-9]+.*[0-9]*");
        System.out.println("strResult"+strResult);
        if(strResult==false){
            amount=0;
        }else {
            amount=Double.parseDouble(cash);
        }
        //分享赚
        if(userNoReCommendId<=0){//没有推荐人默认为零散会员编号id为62240
            userNoReCommendId=62240;
        }
        if(userNoReCommendId>0){//是否有推荐人
            double orderProfit=order.getOrderProfit();//订单利润
            double shareEaring=0.00;
            System.out.println("recommendCommission:"+recommendCommission);
            System.out.println(userRank.toString()+"----");
            if(recommendCommission-userRank.getCommission()>0){
                shareEaring=orderProfit*(recommendCommission-userRank.getCommission())/100;
            }
            if(shareEaring>0){
                FinaceToData finaceToDataRe = new FinaceToData();
                finaceToDataRe.setUserId(userNoReCommendId);//推荐人用户编号Id
                finaceToDataRe.setFinaceType("888");
                finaceToDataRe.setRemark("分享赚"+orderNo);
                finaceToDataRe.setClassify(1);
                finaceToDataRe.setFinaceTime(Timestamp.valueOf(date1));//时间
                finaceToDataRe.setAmount(new BigDecimal(shareEaring));//积分
                finaceToDataRe.setBalance(new BigDecimal(shareEaring+recommendBalance));
                finaceToDataRe.setOpratorUId(userNoReCommendId);
                int row1 = finaceService.insertFinaceData(finaceToDataRe);
                if(row1<=0){
                    bools=false;
                    System.out.println("12");
                    Logger logger= LoggerFactory.getLogger("12"+orderNo);
                    //throw new RuntimeException();
                }
                FinaceTotal finaceTotal4=new FinaceTotal();
                finaceTotal4.setOpratorId(userNoReCommendId);
                finaceTotal4.setBalance(recommendBalance+shareEaring);
                finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                finaceTotal4.setOpratorUId(userNoReCommendId);
                finaceTotal4.setUserId(userNoReCommendId);
                finaceTotal4.setfType("1");
                int recommendF;
                if(recommendFId>0){
                    finaceTotal4.setfId(recommendFId);
                    recommendF=finaceTotalService.updateByPrimaryKey(finaceTotal4);
                }else {
                    recommendF=finaceTotalService.insertSelective(finaceTotal4);
                }
                if(recommendF<=0){
                    bools=false;
                    System.out.println("122");
                    Logger logger= LoggerFactory.getLogger("122"+orderNo);
                    //throw new RuntimeException();
                }
            }

        }
        //分享赚


        if(amount>0){//现金支付是否大于0
            FinaceToData finaceToData = new FinaceToData();
            finaceToData.setUserId(userNoId);//用户编号Id
            finaceToData.setFinaceType("777");
            finaceToData.setRemark("充值"+orderNo);
            finaceToData.setClassify(1);
            finaceToData.setFinaceTime(Timestamp.valueOf(date1));//时间
            finaceToData.setAmount(BigDecimal.valueOf(amount));//积分
            //用户积分的余额
            finaceToData.setBalance(BigDecimal.valueOf(finaceTotal.getBalance1() + amount));
            finaceToData.setOpratorUId(userNoId);
            int res = finaceService.insertFinaceData(finaceToData);
            if(res<=0){
                bools=false;
                System.out.println("Classify1");
                Logger logger= LoggerFactory.getLogger("Classify1"+orderNo);
                //throw new RuntimeException();
            }
        }
        BigDecimal amount1;
        if(order.getRealPay()!=null&&order.getFreight()!=null){
            Boolean strResult1 = order.getRealPay().toString().matches("-?[0-9]+.*[0-9]*");
            Boolean strResult2 = order.getFreight().toString().matches("-?[0-9]+.*[0-9]*");
            if(strResult1==false||strResult2==false){
                amount1=BigDecimal.valueOf(0);
            }else {
                amount1=BigDecimal.valueOf(order.getRealPay()).add(order.getFreight());
            }
        }else {
            amount1=BigDecimal.valueOf(0);
        }
        if(amount1.doubleValue()>0){//实际支付总金额
            System.out.println("Classify1a");
            FinaceToData finaceToData1 = new FinaceToData();
            finaceToData1.setUserId(userNoId);//用户编号Id
            finaceToData1.setFinaceType("111");
            finaceToData1.setRemark("支出"+orderNo);
            finaceToData1.setClassify(1);
            finaceToData1.setFinaceTime(Timestamp.valueOf(date1));//时间
            BigDecimal costinter=order.getCostInter()==null?BigDecimal.valueOf(0):order.getCostInter();
            BigDecimal am=amount1.subtract(costinter);
            finaceToData1.setAmount(new BigDecimal(-am.doubleValue()));//积分
            balance=(finaceTotal.getBalance1()+amount+costinter.doubleValue())-amount1.doubleValue();
            finaceToData1.setBalance(BigDecimal.valueOf(balance));
            finaceToData1.setOpratorUId(userNoId);
            int res1 = finaceService.insertFinaceData(finaceToData1);
            if(res1<=0){
                bools=false;
            }else {
                //更新财务余额
                FinaceTotal finaceTotal4=new FinaceTotal();
                finaceTotal4.setOpratorId(userNoId);
                finaceTotal4.setBalance(balance);
                finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                finaceTotal4.setOpratorUId(userNoId);
                finaceTotal4.setUserId(userNoId);
                finaceTotal4.setfType("1");
                int cosRow;
                if(finaceTotal.getfId1()>0){
                    finaceTotal4.setfId(finaceTotal.getfId1());
                    cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                }else {
                    cosRow =finaceTotalService.insertSelective(finaceTotal4);
                }
                if (cosRow <= 0) {
                    bools=false;
                    System.out.println("Classify1c");
                    Logger logger= LoggerFactory.getLogger("Classify1c"+orderNo);
                    //消费积分扣除有误，支付失败!
                    //throw new RuntimeException();
                }
            }
        }
        if(order.getCostInter()!=null){//订单实际支付使用的消费积分
            if(order.getCostInter().doubleValue()>0){
                FinaceToData finaceToData2 = new FinaceToData();
                finaceToData2.setUserId(userNoId);//用户编号Id
                finaceToData2.setFinaceType("111");
                finaceToData2.setRemark("支出"+orderNo);
                finaceToData2.setClassify(4);
                finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal amount2=order.getCostInter();
                finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance4()) - amount2.doubleValue()));
                finaceToData2.setOpratorUId(userNoId);
                int res2 = finaceService.insertFinaceData(finaceToData2);
                if(res2<=0){
                    //消费积分扣除有误
                    bools=false;
                    System.out.println("Classify4");
                    Logger logger= LoggerFactory.getLogger("Classify4"+orderNo);
                    //throw new RuntimeException();
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setfId(finaceTotal.getfId4());
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(((finaceTotal.getBalance4()) - amount2.doubleValue()));
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("4");
                    int cosRow;
                    if(finaceTotal.getfId4()>0){
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        bools=false;
                        System.out.println("Classify4a");
                        Logger logger= LoggerFactory.getLogger("Classify4a"+orderNo);
                        //消费积分扣除有误，支付失败!
                        //throw new RuntimeException();
                    }
                }
            }
        }
        if(order.getCoupon()!=null){
            if(order.getCoupon().doubleValue()>0){
                FinaceToData finaceToData2 = new FinaceToData();
                finaceToData2.setUserId(userNoId);//用户编号Id
                finaceToData2.setFinaceType("111");
                finaceToData2.setRemark("支出"+orderNo);
                finaceToData2.setClassify(2);
                finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal amount2=order.getCoupon();
                finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance2()) - amount2.doubleValue()));
                finaceToData2.setOpratorUId(userNoId);
                int res2 = finaceService.insertFinaceData(finaceToData2);
                if(res2<=0){
                    //购物券扣除有误
                    bools=false;
                    System.out.println("Classify2b");
                    Logger logger= LoggerFactory.getLogger("Classify2b"+orderNo);
                    //throw new RuntimeException();
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setfId(finaceTotal.getfId2());
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(((finaceTotal.getBalance2()) - amount2.doubleValue()));
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("2");
                    int cosRow;
                    if(finaceTotal.getfId2()>0){
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        bools=false;
                        System.out.println("Classify2c");
                        Logger logger= LoggerFactory.getLogger("Classify2c"+orderNo);
                        //消费积分扣除有误，支付失败!
                        //throw new RuntimeException();
                    }
                }
            }
        }
        if(order.getCashCoupon()!=null){
            if(order.getCashCoupon().doubleValue()>0){
                FinaceToData finaceToData2 = new FinaceToData();
                finaceToData2.setUserId(userNoId);//用户编号Id
                finaceToData2.setFinaceType("111");
                finaceToData2.setRemark("支出"+orderNo);
                finaceToData2.setClassify(3);
                finaceToData2.setFinaceTime(Timestamp.valueOf(date1));//时间
                BigDecimal amount2=order.getCashCoupon();
                finaceToData2.setAmount(new BigDecimal(-amount2.doubleValue()));//
                finaceToData2.setBalance(BigDecimal.valueOf((finaceTotal.getBalance3()) - amount2.doubleValue()));
                finaceToData2.setOpratorUId(userNoId);
                int res2 = finaceService.insertFinaceData(finaceToData2);
                if(res2<=0){
                    bools=false;
                    System.out.println("Classify3a");
                    Logger logger= LoggerFactory.getLogger("Classify3a"+orderNo);
                    //代金券扣除有误
                    //throw new RuntimeException();
                }else {
                    //更新财务余额
                    FinaceTotal finaceTotal4=new FinaceTotal();
                    finaceTotal4.setfId(finaceTotal.getfId3());
                    finaceTotal4.setOpratorId(userNoId);
                    finaceTotal4.setBalance(((finaceTotal.getBalance3()) - amount2.doubleValue()));
                    finaceTotal4.setChanggeTime(new Timestamp(System.currentTimeMillis()));
                    finaceTotal4.setOpratorUId(userNoId);
                    finaceTotal4.setUserId(userNoId);
                    finaceTotal4.setfType("3");
                    int cosRow;
                    if(finaceTotal.getfId3()>0){
                        cosRow =finaceTotalService.updateByPrimaryKeySelective(finaceTotal4);
                    }else {
                        cosRow =finaceTotalService.insertSelective(finaceTotal4);
                    }
                    if (cosRow <= 0) {
                        bools=false;
                        System.out.println("Classify3b");
                        Logger logger= LoggerFactory.getLogger("Classify3b"+orderNo);
                    }
                }
            }
        }
        //返还折扣券保存到数据库返finance3_table
        Integer cashCouponMul = 0;
        String financeName = "";
        if(config!=null){
            if(config.getCashcouponmul()!=null){
                cashCouponMul = config.getCashcouponmul();//返折扣券的倍数 ---2倍
            }
            if(config.getFinacename3()!=""||config.getCashcouponmul()!=null){
                financeName = config.getFinacename3();//返回----折扣券的名称
            }
        }
        if(cashCouponMul>0){
            int resf = FinaceMethods.insertFinaceU(3, BigDecimal.valueOf(order.getBackCashcoupon() * cashCouponMul), userNoId, order.getOrderNo() + "返" + financeName, userNoId, 999);
        }
        //更新会员等级
        if (memberLevel == 19) {
            userNo1.setRank(16);
            int resu = sysUserNoService.updateByPrimaryKeySelective(userNo1);
            if (resu <= 0) {
                //日志or数据库
                bools=false;
                System.out.println("bbbb");
                Logger logger= LoggerFactory.getLogger("bbbb"+orderNo);
                //throw new RuntimeException();
            }
        }
        order.setOrderStatus("702");
        order.setPayStatus("1");
        order.setPayTime(new Date());
        //添加记录运营成本到用户业绩表
        double opratorCost=0.00;//订单运营成本
        UserNoAchievement userNoAchievement=new UserNoAchievement();
        userNoAchievement.setOpratorCostSign("0");//为结算的业绩标志
        userNoAchievement.setUserNoId(memberUserId);
        userNoAchievement.setPayTime(new Timestamp(order.getpOrderTime().getTime()));
        if(order!=null&&order.getOpratorCost()!=null){
            order.getOpratorCost().doubleValue();
        }
        userNoAchievement.setOrderId(order.getOrderId());
        userNoAchievement.setOrderOpratorCost(opratorCost);
            if(opratorCost>0) {
                //int achievementRow = userNoAchievementService.insertSelective(userNoAchievement);
                //添加记录运营成本到用户业绩表
            }

        orderService.activity(order,memberUserId+"",userRank.getCommission(),userNoReCommendId,balance);
            Integer res3=orderService.updateByPrimaryKeySelective(order);
            if(res3<=0){
                bools=false;
            }

    }
    }


    public void checkOrder(){
        List<Order> orders=orderService.selectAll().stream().filter(c ->(c.getOrderStatus().equals("702"))).collect(Collectors.toList());
        int usernoid=0;
        int reusernoid=0;
        double recommendCommission=0;
        double commendCommission=0;
        double shareEaring=0.00;
        for (Order order:orders) {
            //用户
            usernoid=order.getUserId()==null?0:order.getUserId();
            if(usernoid>0){
                UserNo userNo=sysUserNoService.selectByPrimaryKey(usernoid);
                if(userNo!=null){
                    int userRank=userNo.getRank()==null?0:userNo.getRank();
                    UserRank userRank1=userRankService.selectByPrimaryKey(userRank);
                    if(userRank1!=null){
                        commendCommission=userRank1.getCommission()==null?0:userRank1.getCommission();
                    }
                    reusernoid=userNo.getRecommend()==null?0:userNo.getRecommend();
                }
            }
            //分享人
            UserNo reuserNo=sysUserNoService.selectByPrimaryKey(reusernoid);
            if(reuserNo!=null){
                int reuserRank=reuserNo.getRank()==null?0:reuserNo.getRank();
                UserRank userRank2=userRankService.selectByPrimaryKey(reuserRank);
                if(userRank2!=null){
                    recommendCommission=userRank2.getCommission()==null?0:userRank2.getCommission();
                }
            }
            double orderProfit=order.getOrderProfit()==null?0:order.getOrderProfit();//订单利润
            double inter=order.getInter()==null?0:order.getInter().doubleValue();
            double costinter=order.getCostInter()==null?0:order.getCostInter().doubleValue();
            double freight=order.getFreight()==null?0:order.getFreight().doubleValue();
            double realPay=order.getRealPay()==null?0:order.getRealPay().doubleValue();
            double membetSave=order.getMemberSave()==null?0:order.getMemberSave();
            double coupon=order.getCoupon()==null?0:order.getCoupon().doubleValue();
            double cashcoupon=order.getCashCoupon()==null?0:order.getCashCoupon().doubleValue();


            double cash=(realPay+freight-inter-costinter-membetSave-coupon-cashcoupon);

            if(recommendCommission-commendCommission>0){
                shareEaring=orderProfit*(recommendCommission-commendCommission)/100;
            }

        }
    }

}
